from django.utils.deprecation import MiddlewareMixin
from django.http import HttpResponseRedirect

from .models import UserProfile


class UserProfileMiddleware(MiddlewareMixin):

    def process_request(self, request):
        # 统一验证是否登陆
        # return None 或者不写return 才会继续往下执行
        if request.path == '/userprofile/index/' or request.path == '/admin/':
            return None
        ticket = request.COOKIES.get('ticket')
        if not ticket:
            return HttpResponseRedirect('/userprofile/index/')

        users = UserProfile.objects.filter(u_ticket=ticket)
        if not users:
            return HttpResponseRedirect('/userprofile/index/')
        # 在request中存储当前登陆的用户
        request.user = users[0]